package com.zzx.es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.Arrays;

/**
 * @ClassName: com.zzx.es.ESTest_Client
 * @Description: ES批量文档创建测试类
 * @Author zhouzhixin
 * @Date 2021/8/13
 * @Version 1.0
 */
public class ESTest_Doc_Create_Batch {
    public static void main(String[] args) {
        // 建立可自动关闭的连接
        try (RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
        )) {
            // 批量插入数据
            BulkRequest request = new BulkRequest();
            request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zs", "sex", "1", "age", 18));
            request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "ls", "sex", "2", "age", 18));
            request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "ww", "sex", "1", "age", 28));
            request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "zl", "sex", "2", "age", 30));
            request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "tq", "sex", "1", "age", 16));
            request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "lb", "sex", "2", "age", 22));
            // 发送请求
            BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
            // 返回结果
            System.out.println(response.getTook());
            System.out.println(Arrays.toString(response.getItems()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
